/* eslint-disable no-param-reassign */
import { uploadRequst } from './request';
import global from './global';
import ServiceInfoManager from './ServiceInfoManager';
import { getAppIDInfo } from '@/config/template';
import Taro from '@tarojs/taro';

export default async function apiUploadRequst(
  options: IRequestOptions,
  token = true
) {
  const url = await ServiceInfoManager.uploadApiUrl();
  options.headers = {
    'Content-Type': 'multipart/form-data',
  };
  if (token) {
    (options.headers as IRequestHeaders).Authorization = global.token;
  }
  return uploadRequst(url, { ...options, timeout: 20 * 1000 }).then((result) => {
    const { data, success } = result;
    let realSuccess = false;
    let msg = '';
    let resultCode;
    let resultData = {};
    if (success) {
      let { code } = data;
      const { message } = data;

      code = parseInt(code, 10);
      // 请求成功，并且服务器返回200才算是真正的成功
      if (code && code === 200) {
        realSuccess = true;
        resultCode = 200;
        resultData = data.data;
        console.log(`aep result success ${url}`, result);
      } else {
        msg = message;
        resultCode = code || 1; // 服务器返回错误
        console.log(`aep result error ${url}`, result);
      }
    } else {
      resultCode = 0; // 网络请求发生错误
      /**
       * 提示网络错误
       */
      console.log(`aep result error ${url}`, result);
    }
    const compiledResult = {
      code: resultCode,
      message: msg,
      success: realSuccess,
      data: resultData,
    };
    return compiledResult;
  });
}



export async function cozeUploadRequst(
  path: string,
  options: IRequestOptions,
) {
  const filePath = options.filePath
  if (filePath.startsWith('http')) {
    // 先下载到本地
    const res = await Taro.downloadFile({
      url: filePath,
    })
    console.log('resresresres', res)
    if (res.statusCode === 200) {
      options.filePath = res.tempFilePath
    } else {
    }
  }
  const url = await ServiceInfoManager.getCozeApiUrl();
  let appID = getAppIDInfo().appId;

  options.headers = {
    'Content-Type': 'multipart/form-data',
    'X-Gizwits-Application-Id': appID,
  };
  options.headers['X-Gizwits-User-Token'] = global.token;

  return uploadRequst(url + path, { ...options }).then((result) => {
    return result
  });
}